const querystring = require('querystring');
const { getPostData } = require('./util');
const handelBlogRouter = require('./router/blog');
const handelUserRouter = require('./router/user');

const serverHandel = (req, res) => {
  res.setHeader('Content-type', 'application/json');
  req.path = req.url.split('?')[0];
  req.query = querystring.parse(req.url.split('?')[1]);

  getPostData(req, res).then((postData) => {
    req.body = postData;

    // 处理博客路由
    const blogResult = handelBlogRouter(req, res);
    if (blogResult) {
      blogResult.then((blogData) => {
        res.end(JSON.stringify(blogData));
      });
      return;
    }

    // 处理用户路由
    const userData = handelUserRouter(req, res);
    if (userData) {
      res.end(JSON.stringify(userData));
      return;
    }
    res.writeHead(404, { 'Content-Type': 'text/plain' }).end('404 Not Found');
  });
};
module.exports = serverHandel;
